package com.lian.aieduc.handler;

import com.lian.aieduc.manager.WebSocketSessionManager;
import jakarta.websocket.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class WebSocketHandler extends TextWebSocketHandler {

    private static Map<String, WebSocketSession> sessionMap = new HashMap<>();
    private Session session;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 当WebSocket连接建立时的处理逻辑
        System.out.println("WebSocket连接已建立：" + session.getId());
        sessionMap.put(session.getId(), session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 处理接收到的文本消息
        String payload = message.getPayload();
        System.out.println("收到消息：" + payload);
        System.out.println("收到消息 id：" + session.getId());
        // 调用发送给所有客户端（除发送者自身）的方法
        sendToAllClient(payload, session.getId());
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        // 处理传输错误
        System.out.println("WebSocket传输错误：" + session.getId() + "，错误信息：" + exception.getMessage());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 当WebSocket连接关闭时的处理逻辑
        System.out.println("WebSocket连接已关闭：" + session.getId() + "，关闭状态：" + status.getCode() + " - " + status.getReason());
        // 从sessionMap中移除关闭的会话
        sessionMap.remove(session.getId());
    }

    /**
     * 向除了发送者自身之外的所有已连接客户端发送消息
     *
     * @param message 要发送的消息内容
     * @param fromSid 发送者的会话ID
     */
    public void sendToAllClient(String message, String fromSid) {
        Collection<WebSocketSession> sessions = sessionMap.values();
        for (WebSocketSession webSocketSession : sessions) {
            if (!webSocketSession.getId().equals(fromSid)) {
                try {
                    webSocketSession.sendMessage(new TextMessage(message));
                } catch (IOException e) {
                    log.error("向客户端发送消息时出错，客户端会话ID: {}", webSocketSession.getId(), e);
                }
            }
        }
    }
}